package consume.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author Kevin
 * @date 2023/6/11 12:46
 * @description 监听工作队列模式消息
 * 1. 需要在配置文件里配置签收模式
 **/
@Slf4j
@Component
public class WorkListener {

  private Integer consume1 = 0;
  private Integer consume2 = 0;

  /**
   * 消费者1
   * @param msg
   * @param deliveryTag 手动签收所需参数
   * @param channel 手动签收所需参数
   */
  @RabbitListener(queuesToDeclare=@Queue("work-queue"))
  public void listener1(String msg,
                       @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag,
                       Channel channel) throws Exception {



    // 模拟器业务处理时间1s
    Thread.sleep(1000);

    // 手动签收
    channel.basicAck(deliveryTag,true);

    consume1++;
    log.info("消费者1监听到工作队列消息--{}，总共消费了{}条消息",msg,consume1);
  }


  /**
   * 消费者2
   * @param msg
   * @param deliveryTag 手动签收所需参数
   * @param channel 手动签收所需参数
   */
  @RabbitListener(queuesToDeclare=@Queue("work-queue"))
  public void listener2(String msg,
                       @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag,
                       Channel channel) throws Exception {

    // 模拟器业务处理时间2s
    Thread.sleep(2000);

    // 手动签收
    channel.basicAck(deliveryTag,true);

    consume2++;
    log.info("消费者2监听到工作队列消息--{}，总共消费了{}条消息",msg,consume2);
  }

}
